AI.Dataindex = Event.$extend({
	__init__: function(options) {
		this.init(options);
	},
	loadConfig: function() {
		var baseFilename = this.casetype ? 'config.' + this.casetype.toLowerCase() + '.js': 'config.default.js';
		var deployedFilename = "";
		if(this.metaprj) {
			deployedFilename = this.metaprj + "." + baseFilename;
		}
		//ai.loadRemotJsCss("/" + contextPath + "/dacp-res/catalog/js/dataplatIcon.js");
		ai.loadRemotJsCss("/" + contextPath + "/dacp-res/catalog/dataindex/js/" + baseFilename);

		if(deployedFilename) {
			var tempConfig = config;
			config = {};
			ai.loadRemotJsCss("/" + contextPath + "/dacp-res/catalog/dataindex/js/" + deployedFilename);
			for(var i in config) {
				console.log(i);
				tempConfig[i] = config[i];
			}
			config = tempConfig;
		}
		
		ai._global_loadfile.pop();
	},
	init: function(options) {
		if (!options.containerId || !$('#' + options.containerId)[0]) {
			alert('未设置容器ID或容器不存在!');
			return;
		}
		this.$container = $('#' + options.containerId);
		//this.advanceFilter = options.advanceFilter||this.advanceFilter;
		this.objtype = options.objtype || this.objtype;
		if(!this.objtype) return;
		this.casetype = options.casetype || this.casetype;
		this.metaprj = options.metaprj || this.metaprj;
		this.meta = new AI.Meta({});
		this.metaModel = this.meta.getMetaModel(this.objtype);
		this.metaInfo = this.metaModel.metaInfo;
		this.loadConfig();
		if(config[this.objtype]['tip']) this.buildGlobalTip(options);
		if(config[this.objtype]["filter"]) this.buildAdvanceFilter(options);
		if(config[this.objtype]['list']) {
			this.buildMainContent(options);
			var list = config[this.objtype]['list'];
			if(list.cardElementClick) this.buildCardElementClickEvent(list.cardElementClick);
		}
		
		
		
	},
	buildGlobalTip: function(options) { ///高级过滤区
		var tip = config[this.objtype]["tip"];
		var id = options.containerId+'_globaltip';
		var html = '<div id="' + id + '" class="alert alert-info alert-dismissible" role="alert">' + 
  						'<button type="button" class="close" data-dismiss="alert">' + 
  							'<span aria-hidden="true">&times;</span>' +
  							'<span class="sr-only">Close</span>' +
  						'</button>' +
  						// '<strong>Warning!</strong> Better check yourself, youre not looking too good.' + 
  						tip +
					'</div>';

		var tipDiv = $(html);
		tipDiv.css({
			'margin-bottom': '4px',
			'margin-top': '6px'
		});
		tipDiv.find("button.close").css({
			'position': 'relative',
			'top': 'auto',
			'right': 'auto',
			'padding-right': '10px',
			'opacity': 'unset'
		});

		// this.$container.append('<div id="'+options.containerId+'_globaltip" class="global-tip">'+tip+'</div>');
		this.$container.append(tipDiv);
	},
	buildAdvanceFilter: function(options) { ///高级过滤区
		var configItems = config[this.objtype]["filter"];
		if (!configItems || configItems.length == 0) return;
		if (options.filterParam) {
			for (var i = 0; i < configItems.length; i++) {
				var item = configItems[i];
				if (!item.storesql) continue;
				if (item.storesql.toLowerCase().indexOf("select ") >= 0) {
					for(key in options.filterParam){
//						item.storesql = item.storesql.replace('{'+key+'}',options.filterParam[key]);
						//item.storeval = options.filterParam[key];
					}
				}
			}
		}
//		if (options.bindDefaultValue) configItems = options.bindDefaultValue(configItems);
//		if (options.detailFilterSql) configItems = options.detailFilterSql(configItems);
		this.$container.append('<div id="'+options.containerId+'_advance_filterarea" class="advance-filterarea"></div>');
		var self = this;
		new AI.AdvanceFilter({
			//一个页面可能存在多个AdvanceFilter,避免影响其他
			containerId:  options.containerId + '_advance_filterarea',
			hovertype: 'show',
			configItems: configItems,
			onChange: function(where, vals) {
				var newsql = self.querysql;
				if (where && where.length > 0) {
					var strWhere = where.join(" and ");
					if (newsql.toLowerCase().indexOf(" where ") > 0) newsql += " and " + strWhere
					else newsql += " where " + strWhere
				}
				self.listView.reload(newsql);
				console.log(newsql);
			}
		});
		$("#advance_filterarea>.pull-right").hide();
		if (options.bindSearchElem) options.bindSearchElem();
	},
	getListConfig: function(containerId) {
		this.$container.append('<div id="'+containerId+'" class="datalist"></div>');
		var cfg = config[this.objtype]['list'];
		if (!cfg.title) cfg.title = this.metaInfo.objname;
		if (!cfg.detailurl) cfg.detailurl = this.metaInfo.detailurl;
		if (!cfg.sql) cfg.sql = "select * from " + this.metaInfo.tabname;
		if (!cfg.tpl) cfg.tpl = this.meta.getMetaProPerty(objtype, "viewcarttpl");
		if (!cfg.toolbarconfig) cfg.toolbarconfig = [];
		return cfg;
	},
	buildMainContent: function(options) {
		var viewcarttpl = 'viewcarttpl';
		var containerId = options.containerId+'_datalist';
		var cfg = this.getListConfig(containerId);
		if (options.filterParam) {
			for(key in options.filterParam){
				cfg.sql = cfg.sql.replaceAll('{'+key+'}',options.filterParam[key]);
			}
		}
//		cfg.sql = options.detailSqlForever ? options.detailSqlForever(cfg.sql) : cfg.sql;
//		var _querysql = options.detailSqlTemp ? options.detailSqlTemp(cfg.sql,config[this.objtype]["filter"]) : cfg.sql;
		var sql = rebuildSqlByPermission(cfg.sql,metadbListPermission(),"数据权限");
		this.itemStore = new AI.JsonStore({
			sql: sql,
			pageSize: 50,
			key: "XMLID"
		});
		this.querysql = cfg.sql;
		var self = this;
		var listView = new AI.MetaList({
			//一个页面可能存在多个listView,避免影响其他
			containerId: containerId,
			store: this.itemStore,
			objtype: this.objtype,
			title: cfg.title || this.metaInfo.objname,
			bodyHtml: '<div class="repeater-canvas col-md-12" style="padding-left:1px;padding-right:1px;height:100%;overflow:auto"></div> ',
			columns: cfg.columns,
			show: true,
			card: {
				tpl: cfg.tpl
			},
			preParaDataStore: function(store) {
				for (var i = 0; i < self.itemStore.getCount(); i++) {
					var r = self.itemStore.getAt(i);
					r.set('ROWINDEX', i);
					r.set('OBJCNTYPE', self.transCode(typeStore, 'OBJTYPE', 'OBJNAME', r.get('OBJTYPE')));
					r.set('DBCNNAME', self.transCode(baseStore, 'DBNAME', 'CNNAME', r.get('DBNAME')));
					var cycle = self.transCode(cycleStore, 'ROWCODE', 'ROWNAME', r.get('CYCLETYPE'));
					r.set('CYCLECNTYPE', cycle);
					r.set('TOPICCNNAME', self.transCode(topicStore, 'RULECODE', 'RULENAME', r.get('TOPICNAME')));
					if (r.get("FIELDNUM") == null) {
						r.set('FIELDCNNUM', '--');
					} else {
						r.set('FIELDCNNUM', r.get("FIELDNUM"));
					}
					if (r.get("ROWNUM_VAL") == null) {
						r.set('ROWNUM_CNVAL', '--');
					} else {
						r.set('ROWNUM_CNVAL', r.get("ROWNUM_VAL"));
					}
					r.set('STATECN',getRowName('DIM_STATE',r.get('STATE')));
					
				}
			},
			// dblClick: function(objid, objtype) {
			// MainSheet.addTabSheet(objid.substr(0,3), objid.substr(0,5), "/me/ftl/datastore/tabDetail",true,true);
			// return false;
			// },
			click: function(e) {
				var $this = $(e.currentTarget);
				var objtype = $this.attr("OBJTYPE");
				var $this = $(e.currentTarget);
				var objtype = $this.attr("OBJTYPE");
				if (objtype != 'TAB') {
					return false;
				};
				$this.toggleClass('large');

				if ($this.hasClass('large')) {
					if ($('.detail', $this).length == 0) {
						$('.fieldinfo', $this).append(self.getColumnInfo($this.attr("id"))).addClass("detail");
					};

					$(".detail", $this).show();
					$(".detail a").click(function(e) {
						e.stopPropagation();
						var $this = $(e.currentTarget);
						$this.parents('.dacptiles').trigger('dblclick');
					});

					$(".panel-heading", $this).addClass("header-panel");
					$(".dacptiles.panel", $this).addClass("md-col");
					$(".part-two", $this).addClass("color-chg");
					$(".part-two", $this).addClass("class-chg");
					$(".dacptiles .nav>li>a", $this).addClass("color-chg");
					$(".nav>li>a>img", $this).addClass("icon-class");
					$(".text-muted", $this).addClass("color-chg");
					$(".nav i", $this).css("color", "#EFF5FB");
				} else {
					$this.children().show();
					$(".detail", $this).hide();
					$(".panel-heading", $this).removeClass("header-panel");
					$(".dacptiles.panel", $this).removeClass("md-col");
					$(".part-two", $this).removeClass("color-chg");
					$(".part-two", $this).removeClass("class-chg");
					$(".dacptiles .nav>li>a", $this).removeClass("color-chg");
					$(".nav>li>a>img", $this).removeClass("icon-class");
					$(".text-muted", $this).removeClass("color-chg");
					$(".nav i", $this).css("color", "#5CAEA5");
				};
				//if(objtype=='TAB') 
				//$container.isotope('reLayout');
				return false;

			},
			contextMenu: function() {},
			onLoaded: function() {

				$(".repeater-list table td").attr("title", "");
				$(".dacptiles .panel-heading").click(function() {
					return false;
				});
				$(".dacptiles .panel-footer").click(function() {
					return false;
				});

				$("#advance_filter").click(function() {
					var filterAreaIsShow = $("#advance_filterarea").parent().parent().is(":hidden");
					if (filterAreaIsShow) $("#advance_filterarea").parent().parent().show()
					else $("#advance_filterarea").parent().parent().hide();
				});
				//		        self.buildListCardAction();
				//		        self.buildListHeadAction();
				if (this.objtype == 'TAB') self.loadCardIsotope();
				console.log("onLoaded");
				if(this.objtype == "OPENAPI"){
					$("span[sugIndex^=sugIndex_]").each(function(){
						var index=($(this).attr("sugIndex").split("_"))[1];
						for(var i=0;i<index;i++){
							$(this).append("<span class='glyphicon glyphicon-star' style='font-size:10px'></span>");
						}
					});
				}
			},
			//"headerLeftHtml": '<ul class="nav navbar-nav navbar-left" style="height: 30px;"><li><a>全部</a></li><li></li><li><a>最新关注</a></li><li><a>最新推荐</a></li><li><a>最新申请</a></li> ' + '<li><form class="navbar-form  input-s-lg m-t m-l-n-xs hidden-xs" style="margin: 1px 0;"> <div class="form-group"> <div class="input-group input-group-sm"> <span class="input-group-btn">  <input type="text" class="form-control input-sm no-border keyword" placeholder="输入关键字..."><button type="button" class="btn btn-sm btn-icon btn-danger"><i class="fa fa-search"></i></button>  </span> </div> </div> </form></li>' + '<li><a href="#" id="advance_filter"><i class="fa fa-filter"></i>高级过滤</a></li>' + '<li><a href="#"><i class="fa fa-filter"></i>导出</a></li>'
			//+'<li><button type="button" class="btn btn-default btn-sm dropdown" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">    排序方式 <span class="caret"></span>  </button></li>'
			// +'<li><div class="btn-group"> <a type="" class="dropdown-toggle dropdown" data-toggle="dropdown"> Dropdown <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#">Dropdown link</a></li> <li><a href="#">Dropdown link</a></li> <li><a href="#">Dropdown link</a></li> </ul> </div></li>'
			// + '</ul>',
			toolbarconfig: config[this.objtype]['toolbar'] || [],
			// fieldInfoArray:result.fieldInfoArray||[],
			// loadtype: this.casetype ? 'dataindex': 'metaindex'
			loadtype: 'dataindex',
			onLoaded:function(){
				if(cfg.columns.length <=1){
					$('#'+containerId).find('thead').hide();
				}
			}
		});
		this.listView = listView;
		
		this.meta.on("deleteMetaObj",function(){
			listView.reload();
		})
		
		if(cfg.columns.length <=1){
			$('#'+containerId).find('thead').hide();
		}
	},
	buildListHeadAction:function() {
		var self = this;
		var objid = $(".dacptiles.panel.panel-success").attr("id");
		var objInfo = this.meta.getMetaObjBaseInfo(objtype, objid, 'record');
		if (!objInfo) {
			console.log('Error,通过id:' + objid + '未获取到对象!');
			return;
		}
		var dockplace = "rightmenu";
		var actionItems = this.meta.getMetaObjActionItems(objtype, dockplace);
		//$("#card-choose a span").append('<div class="row"></div>');
		var i = 0;
		$(".dacptiles ul").empty();
		for (key in actionItems) {
			i++;
			if (actionItems[key].getright) {
				actionItems[key].disabled = false;
				var result = actionItems[key].getright(objInfo, _UserInfo, this.meta.getMetaInfo(objtype), 'dataindex');
				if (result == 'hide') {
					i--;
					continue;
				};
				if (result == 'disabled') {
					actionItems[key].disabled = true;
				}
			}
			var href = actionItems[key].url;
			var icon = actionItems[key].icon;
			var actName = actionItems[key].name;
			if (i > 4) {
				break;
			}
			$(".dacptiles ul").prepend('<li><a href="#" name="' + key + '" data-toggle="tooltip" data-placement="bottom" title="' + actName + '"><i class="' + icon + '"></i></a></li>');
			// if(i%3==0){
			//   $("#card-choose a span").append('<div class="row"></div>'); 
			// }
		}
		$(".dacptiles ul li a").click(function(e) {
			var $this = $(e.currentTarget);
			var actionkey = $(this).attr('name');
			if (actionkey == 'addMyFav') {
				return false;
			}
			e.stopPropagation();
			objid = $this.parent().parent().parent().parent().attr("id");
			objInfo = self.meta.getMetaObjBaseInfo(objtype, objid, 'record');
			self.listView.metaAction({
				actionkey: $(this).attr('name')
			},
			objInfo);
		});
	},
	buildCardElementClickEvent:function(config){
		var self = this;
		$.each(config,function(key,fun){
			if(typeof fun == "function"){
				self.$container.on("click",key,function(){
					var objid = $(this).parents(".dacptiles.panel.panel-success").attr("id");
					fun(self,objtype,objid);
				});
			}
		})
	},
	buildListCardAction: function() {
		var objid = $(".dacptiles.panel.panel-success").attr("id");
		var objInfo = this.meta.getMetaObjBaseInfo(objtype, objid, 'record');
		if (!objInfo) {
			console.log('Error,通过id:' + objid + '未获取到对象!');
			return;
		}
		var dockplace = "rightmenu";
		var actionItems = this.meta.getMetaObjActionItems(objtype, dockplace);
		//$("#card-choose a span").append('<div class="row"></div>');
		var i = 0;
		$(".dacptiles ul").empty();
		for (key in actionItems) {
			i++;
			if (actionItems[key].getright) {
				actionItems[key].disabled = false;
				var result = actionItems[key].getright(objInfo, _UserInfo, this.meta.getMetaInfo(objtype), 'dataindex');
				if (result == 'hide') {
					i--;
					continue;
				};
				if (result == 'disabled') {
					actionItems[key].disabled = true;
				}
			}
			var href = actionItems[key].url;
			var icon = actionItems[key].icon;
			var actName = actionItems[key].name;
			if (i > 4) {
				break;
			}

			$(".dacptiles ul").prepend('<li><a href="#" name="' + key + '" data-toggle="tooltip" data-placement="bottom" title="' + actName + '"><i class="' + icon + '"></i></a></li>');
			// if(i%3==0){
			//   $("#card-choose a span").append('<div class="row"></div>'); 
			// }
		}
		$(".dacptiles ul li a").click(function(e) {
			var $this = $(e.currentTarget);
			e.stopPropagation();
			objid = $this.parent().parent().parent().parent().attr("id");
			objInfo = meta.getMetaObjBaseInfo(objtype, objid, 'record');
			listView.metaAction({
				actionkey: $(this).attr('name')
			},
			objInfo);
		});
	},
	loadCardIsotope: function() {
		$container = $('#myRepeater .repeater-thumbnail-cont');
		$container.isotope({
			itemSelector: '.thumbnail',
			masonry: {
				columnWidth: 10
			},
			itemPositionDataEnabled: true,
			masonryHorizontal: {
				rowHeight: 240
			},
			cellsByRow: {
				columnWidth: 240,
				rowHeight: 240
			},
			cellsByColumn: {
				columnWidth: 140,
				rowHeight: 120
			}
		});
	},
	transCode: function(dimStore, keyfield, namefield, code) {
		if (dimStore.getCount() > 0) {
			if (code != null) {
				code = code.trim();
				for (var i = 0; i < dimStore.getCount(); i++) {
					if (dimStore.getAt(i).get(keyfield).trim() == code) {
						return dimStore.getAt(i).get(namefield);
					} else {
						continue;
					}
				}
			} else {
				code = '无'
				return code;
			}
		} else {
			return code == null ? '无': code;
		}
		return !code ? '无': code;
	},
	getColumnInfo: function(xmlid) {
		var coldata = ai.getStoreData("select colname,colcnname from column_val where xmlid='" + xmlid + "' order by col_seq");
		var html = "";
		for (var i = 0; i < coldata.length; i++) {
			html += '<div class="col-xs-6"><small pull-left"> <i class="fa fa-clock-o"></i> ' + coldata[i].COLNAME.toLowerCase() + "," + coldata[i].COLCNNAME + '</small></div> ';
			if (i >= 18) {
				html += '<div class="col-xs-6"><a href="#" id="getMoreDetail"><span class="label label-primary pull-left">查看更多>></span></a></div>';
				break;
			}
		};
		return html;
	},
	treeNodeClick: function(id, title, url) {
		console.log(id, title, url);
		if (!url) return false;
		if (url.substr(0, 1) != "/") url = "/" + contextPath + "/" + url;
		var urlParser = $.url(url);
		var opener = urlParser.param("opener") || "content"; ///当前主窗口区替换
		var toUrl = url;
		if (!urlParser.attr('base')) {
			var baseUrl = $.url().attr('base');
			if (url.substr(0, 1) != "/") toUrl = baseUrl + "/" + url
			else toUrl = baseUrl + url
		};
		id = id.replaceAll("_", "").replaceAll("-", "");

		if (opener == "content") $("#frame-right-iframe").attr("src", toUrl)
		else if (opener == "dialog") ai.openDialog("src", toUrl)
		else if (opener == "tabsheet") MainSheet.addTabSheet(id, title, toUrl, true, true);
	},

	dealUrl: function(url, param) {
		if (!param) param = {};
		param['contextPath'] = contextPath;
		param['TEAMCODE'] = paramMap.TEAMCODE;
		for (var key in param) {
			url = url.replace('{' + key + '}', param[key]);
		}
		return url;
	}
});